package com.magnate.software.generator.mybatis.aop;

import com.magnate.software.common.mybatis.anotation.DataSource;
import com.magnate.software.common.mybatis.context.DynamicDataSourceHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

/**
 * 动态数据源切面
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2017/2/9 17:09
 */
@Aspect
@Service("mongoPagingAdvices")
public class DataSourceAspect {

    private final static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("execution (* com.magnate.software.generator.mybatis.mapper.*.*(..))")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();
        String methodName = joinPoint.getSignature().getName();

        Class<?>[] classArray = target.getClass().getInterfaces();

        Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes();
        try {
            Method method = classArray[0].getMethod(methodName, parameterTypes);
            if (method != null && method.isAnnotationPresent(DataSource.class)) {
                DataSource data = method.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
                System.out.println(data.value());
            }

        } catch (Exception e) {
            logger.error("Dynamic DataSource Error", e);
        }
    }

}
